﻿using Furion.EventBus;
using Gardener.Core.EventBus;
using Gardener.Core.NotificationSystem;
using Gardener.Iot.Dtos;
using Gardener.Weighbridge.Impl.Core;

namespace Gardener.Weighbridge.Impl.Subscribes
{
    /// <summary>
    /// 
    /// </summary>
    public class DeviceDataSaveAfterNotificationSubscriber : IEventSubscriber
    {

        private readonly ISystemNotificationService systemNotificationService;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="systemNotificationService"></param>
        public DeviceDataSaveAfterNotificationSubscriber(ISystemNotificationService systemNotificationService)
        {
            this.systemNotificationService = systemNotificationService;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="context"></param>
        [EventSubscribe($"{nameof(EventGroup.SystemNotify)}Gardener.Iot.Dtos.{nameof(DeviceDataSaveAfterNotificationData)}")]
        public async Task Handle(EventHandlerExecutingContext context)
        {
            IEventSource eventSource = context.Source;

            DeviceDataSaveAfterNotificationData deviceData = (DeviceDataSaveAfterNotificationData)eventSource.Payload;
            if(deviceData.DeviceData.DeviceId==null || deviceData.DeviceData.OriginalContent==null || deviceData.DeviceData.OriginalContent.Length==0)
            {
                return;
            }
            WeighbridgeNotificationData notificationData = new WeighbridgeNotificationData(deviceData.DeviceData.DeviceId.Value);
            if (!await systemNotificationService.ExistsDynamicSubscriber(notificationData))
            {
                //无订阅
                return;
            }
            WeighbridgeUploadData? weighbridgeData = WeighbridgeUploadDataParse.Parse(deviceData.DeviceData.OriginalContent);
            notificationData.Data = weighbridgeData;
            //入库
            //发送通知给动态订阅者
            await systemNotificationService.SendToDynamicSubscriber(notificationData);

        }
    }
}
